package wiki.kaizen.cloud.shiro.stateless.shiro;

import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.StringUtils;
import wiki.kaizen.cloud.shiro.stateless.util.ISecurityUtil;
import wiki.kaizen.cloud.shiro.stateless.util.JWTUtil;

import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 无状态Realm
 * @author  xeepoo
 * */
public class StatelessRealm extends AuthorizingRealm {

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof StatelessToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String token = ISecurityUtil.token();
        Claims claims = JWTUtil.parseJWT(token);

        String rolesString = String.valueOf(
            claims.get(JWTUtil.ROLES_KEY)
        );
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(
            Stream.of(
                StringUtils.split(rolesString,',')
            ).collect(Collectors.toSet())
        );

        String permsString = String.valueOf(
            claims.get(JWTUtil.PERMS_KEY)
        );
        info.setStringPermissions(
            Stream.of(
                StringUtils.split(permsString,',')
            ).collect(Collectors.toSet())
        );
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        StatelessToken statelessToken = (StatelessToken)authenticationToken;

        String userCode = statelessToken.getUserCode();
        String token = statelessToken.getToken();

        ISecurityUtil.check(token);//检查token, 发生异常则检查不通过
        return new SimpleAuthenticationInfo(userCode, token, super.getName());
    }
}
